package com.zkthink.ceres.order.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zkthink.base.R;
import com.zkthink.cache.repository.RedisRepositoryImpl;
import com.zkthink.ceres.order.constants.CommentConstant;
import com.zkthink.ceres.order.dao.CommentKeywordMapper;
import com.zkthink.ceres.order.dto.comment.*;
import com.zkthink.ceres.order.entity.CommentKeyword;
import com.zkthink.ceres.order.entity.SensitiveKeyword;
import com.zkthink.ceres.order.service.CommentKeywordService;
import com.zkthink.base.service.SuperServiceImpl;

import com.zkthink.ceres.product.dto.IdQueryDTO;
import com.zkthink.database.mybatis.conditions.Wraps;
import com.zkthink.exception.code.ExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 评价关键词表
 * </p>
 *
 * @author JustArgo
 * @date 2020-07-12
 */
@Slf4j
@Service
public class CommentKeywordServiceImpl extends SuperServiceImpl<CommentKeywordMapper, CommentKeyword> implements CommentKeywordService {

    @Autowired
    private RedisRepositoryImpl redisRepository;

    @Override
    public R<Boolean> addCommentKeyword(AddCommentKeywordDTO addDTO) {
        String keyword = addDTO.getKeyword();
        Integer enabled = addDTO.getEnabled();
        if (StringUtils.isBlank(keyword)) {
            return R.fail(ExceptionCode.ILLEGALA_ARGUMENT_EX.getCode(), "关键词不能为空");
        }
        Long id = null;
        CommentKeyword commentKeyword = baseMapper.selectOne(Wraps.<CommentKeyword>lbQ().eq(CommentKeyword::getKeyword, keyword));
        if (commentKeyword != null) {
            if (commentKeyword.getIsDelete() == 1) {
                commentKeyword.setEnabled(enabled);
                commentKeyword.setIsDelete(0);
                id = commentKeyword.getId();
                baseMapper.updateById(commentKeyword);
            } else {
                return R.fail(ExceptionCode.OPERATION_EX.getCode(), "该关键词已存在,不能重复添加");
            }
        } else {
            CommentKeyword newKeyword = new CommentKeyword();
            newKeyword.setEnabled(enabled);
            newKeyword.setKeyword(keyword);
            baseMapper.insert(newKeyword);
            id = newKeyword.getId();
        }

        redisRepository.getRedisTemplate().opsForZSet().add(CommentConstant.COMMENT_KEYWORD_LIST,keyword,id);

        return R.success();
    }

    @Override
    public R<Boolean> deleteCommentKeyword(IdQueryDTO queryDTO) {
        CommentKeyword commentKeyword = baseMapper.selectById(queryDTO.getId());
        baseMapper.logicDeleteByIds(new ArrayList<>(Arrays.asList(queryDTO.getId())));
        redisRepository.getRedisTemplate().opsForZSet().remove(CommentConstant.COMMENT_KEYWORD_LIST,commentKeyword.getKeyword());
        return R.success();
    }

    @Override
    public R<CommentKeywordPageDTO> findCommentKeywordList(FindKeywordListDTO keywordListDTO) {
        if (keywordListDTO == null) {
            return R.fail(ExceptionCode.ILLEGALA_ARGUMENT_EX);
        }
        CommentKeywordPageDTO pageDTO = new CommentKeywordPageDTO();
        Page<CommentKeyword> pageParam = new Page<>(keywordListDTO.getPageIndex(), keywordListDTO.getPageSize());
        IPage<CommentKeyword> page = baseMapper.selectPage(pageParam,Wraps.<CommentKeyword>lbQ().eq(CommentKeyword::getIsDelete, false)
                .like(StringUtils.isNotBlank(keywordListDTO.getKeyword()), CommentKeyword::getKeyword,
                        keywordListDTO.getKeyword()).orderByDesc(CommentKeyword::getCreateTime));
        pageDTO.setTotal(Integer.valueOf(page.getTotal()+""));
        pageDTO.setCommentKeywordList(page.getRecords());
        return R.success(pageDTO);
    }

    @Override
    public R<Boolean> updateCommentKeywordSetting(UpdateKeywordSettingDTO updateKeywordSettingDTO) {
        CommentKeyword commentKeyword = new CommentKeyword();
        commentKeyword.setEnabled(updateKeywordSettingDTO.getEnabled());
        baseMapper.update(commentKeyword,Wraps.<CommentKeyword>lbQ().eq(CommentKeyword::getIsDelete,false));

        redisRepository.set(CommentConstant.COMMENT_KEYWORD_SETTING,commentKeyword);

        return R.success();
    }

    @Override
    public R<Boolean> updateCommentKeyword(CommentKeyword commentKeyword) {

        CommentKeyword originCommentKeyword = baseMapper.selectById(commentKeyword.getId());

        List<CommentKeyword> list = baseMapper.selectList(Wraps.<CommentKeyword>lbQ()
                .eq(CommentKeyword::getKeyword,commentKeyword.getKeyword())
                .eq(CommentKeyword::getIsDelete,false));
        if(list.size()>0 && !list.stream().map(CommentKeyword::getId).collect(Collectors.toList()).contains(commentKeyword.getId())){
            return R.fail(ExceptionCode.ILLEGALA_ARGUMENT_EX.getCode(),"已存在该关键词");
        }
        //如果和原来的不相等，并且现在是启用状态，需要删除redis旧关键词缓存，并且新增新关键词缓存
        if(!originCommentKeyword.getKeyword().equals(commentKeyword.getKeyword())
                && commentKeyword.getEnabled()==1){
            redisRepository.getRedisTemplate().opsForZSet().remove(CommentConstant.COMMENT_KEYWORD_LIST,originCommentKeyword.getKeyword());
            redisRepository.getRedisTemplate().opsForZSet().add(CommentConstant.COMMENT_KEYWORD_LIST,commentKeyword.getKeyword(),commentKeyword.getId());
        }
        baseMapper.updateById(commentKeyword);
        return R.success();
    }

    @Override
    public Integer initCommentKeyword(){
        List<CommentKeyword> keywordList = baseMapper.selectList(Wraps.<CommentKeyword>lbQ().eq(CommentKeyword::getIsDelete,false));
        if(keywordList!=null){
            CommentKeyword setting = new CommentKeyword();
            setting.setEnabled(keywordList.get(0).getEnabled());
            redisRepository.set(CommentConstant.COMMENT_KEYWORD_SETTING,setting);

            for(CommentKeyword keyword:keywordList){
                redisRepository.getRedisTemplate().opsForZSet().add(CommentConstant.COMMENT_KEYWORD_LIST,keyword.getKeyword(),keyword.getId());
            }
        }
        return keywordList.size();
    }
}
